package org.millioncall.yueyoga.admin.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.export.AbstractExcelExportTemplate;
import org.millioncall.yueyoga.admin.export.MemberExportTemplate;
import org.millioncall.yueyoga.admin.model.Area;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.admin.model.Clazz;
import org.millioncall.yueyoga.admin.model.Goods;
import org.millioncall.yueyoga.admin.model.GoodsOrderDetail;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Hall;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.MemberAdvance;
import org.millioncall.yueyoga.admin.model.MemberLevel;
import org.millioncall.yueyoga.admin.model.Product;
import org.millioncall.yueyoga.admin.model.Status;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.AreaService;
import org.millioncall.yueyoga.admin.service.CheduleService;
import org.millioncall.yueyoga.admin.service.ClazzService;
import org.millioncall.yueyoga.admin.service.CoachService;
import org.millioncall.yueyoga.admin.service.EarlyExperienceService;
import org.millioncall.yueyoga.admin.service.GoodsOrderDetailService;
import org.millioncall.yueyoga.admin.service.GoodsService;
import org.millioncall.yueyoga.admin.service.HallService;
import org.millioncall.yueyoga.admin.service.MemberLevelService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.PlaceService;
import org.millioncall.yueyoga.admin.service.ProductRemainingService;
import org.millioncall.yueyoga.admin.service.ProductService;
import org.millioncall.yueyoga.admin.service.RemainingService;
import org.millioncall.yueyoga.admin.service.StatusService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.millioncall.yueyoga.common.utils.ZhuwNum62;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

//--created by lisj on 2014.03.06
@Controller
public class MemberAction extends BaseAction {
	public static final DateFormat FILE_DATEFORMAT = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	private static Logger logger = LoggerFactory.getLogger(MemberAction.class);
	private MemberService memberService;
	private RemainingService remainingService;
	private ProductRemainingService productRemainingService;
	private AreaService areaService;
	private StatusService statusService;
	private MemberLevelService memberLevelService;
	private HallService hallService;
	private GoodsOrderDetailService goodsOrderDetailService;
	private GoodsService goodservive;
	private EarlyExperienceService earlyExperienceService;
	private ClazzService clazzService;
	private CoachService coachService;
	private CheduleService cheduleService;
	private PlaceService placeService;
	private UserService userService;
	private ProductService productService;

	/**
	 * 查询会员总数
	 */
	@RequestMapping(value = "/ajaxGetTotalMembers.jhtml", method = RequestMethod.POST)
	public void ajaxGetTotalMembers(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "-";

		int totalMembers = memberService.getTotalMembers();
		msg = String.valueOf(totalMembers);

		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 高级搜索会员 */
	@RequestMapping(value = "/ajaxAdvSearchMember.jhtml")
	public void advSearchMember(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String strLimit = request.getParameter("limit");

		String exp = request.getParameter("expression");
		String expType = request.getParameter("expType");

		String msg = "";

		int limit = Integer.MAX_VALUE;

		try {
			limit = Integer.parseInt(strLimit);
		} catch (NumberFormatException e) {
			limit = Integer.MAX_VALUE;
		}

		if (StringUtils.isBlank(exp)) {
			msg = "{'success':false, 'msg':'表达式不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (StringUtils.isBlank(expType)) {
			msg = "{'success':false, 'msg':'表达式类型不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		// 用于过滤会员的条件map
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hallcode", this.getUser(request).getOrganizationId());

		// 条件表达式
		// 在此组装条件表达式
		AviatorExpression expression = new AviatorExpression();
		expression.setExpression(exp);
		// 条件表达式的map
		Map<String, Object> aviatorParams = new HashMap<String, Object>();
		aviatorParams.put(GlobalConstants.RESULT_ROW_MODEL_KEY, expType);

		List<MemberAdvance> members = this.memberService
				.getAllMembersWithAviatorAdvance(params, expression,
						aviatorParams, limit);

		if (members.size() > 0) {
			String json = JSON.toJSONStringWithDateFormat(members,
					"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
			msg = "{'success':true, 'total':'" + members.size() + "', 'items':"
					+ json + "}";
		} else {
			msg = "{'success':true, 'total':'0', 'items':''}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	// 导入会员
	@RequestMapping(value = "/importMember.jhtml")
	public String importMember(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		User user = this.getUser(request);
		File file = new File(request.getServletContext().getRealPath("/")
				+ GlobalConstants.APP_VIEW_PATH + "/会员导入模板.xlsx");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("organizationId", user.getOrganizationId());
		map.put("userId", user.getId());
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		this.memberService.importMemberFromExcel(file, map);
		return "redirect:searchMember.jhtml";
	}

	// 下载导入会员模板
	@RequestMapping(value = "/downloadTemplate.jhtml")
	public void downloadTemplate(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {

		File file = new File(request.getServletContext().getRealPath("/")
				+ GlobalConstants.APP_VIEW_PATH + "/会员导入模板.xlsx");
		// 文件名
		String fileName = "会员导入模板.xlsx";
		BufferedOutputStream output = null;
		BufferedInputStream input = null;
		try {
			AbstractExcelExportTemplate.setFileDownloadHeader(request,
					response, fileName);
			response.setContentLength((int) file.length());
			byte[] buffer = new byte[4096];// 缓冲区
			output = new BufferedOutputStream(response.getOutputStream());
			input = new BufferedInputStream(new FileInputStream(file));
			int n = -1;
			// 遍历，开始下载
			while ((n = input.read(buffer, 0, 4096)) > -1) {
				output.write(buffer, 0, n);
			}
			output.flush(); // 不可少
			response.flushBuffer();// 不可少

		} catch (Exception e) {
			// 异常自己捕捉
		} finally {
			// 关闭流，不可少
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 添加会员
	@RequestMapping(value = "/addMember.jhtml", method = RequestMethod.POST)
	public String addmember(ModelMap map, HttpServletRequest request,
			HttpServletResponse response) {
		User user = this.getUser(request);
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map1.put("groups", groupIds);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		if (StringUtils.isBlank(request.getParameter("cardNumber"))) {
			map1.put("columnName", "cardNumber");
			map1.put("value", request.getParameter("cardNumber"));
			if (memberService.findByCardNumber(map1) != null) {
				map.put("msg", "会员卡号已存在!");
				return this.toAddMember(map, request, response);
			}
		}
		map1.put("columnName", "phone");
		map1.put("value", request.getParameter("phone"));
		if (memberService.findByPhone(map1) != null) {
			map.put("msg", "会员手机号已存在!");
			return this.toAddMember(map, request, response);
		}
		map.put("cardNumber", request.getParameter("cardNumber"));
		String name = request.getParameter("name");
		if (StringUtils.isBlank(name)) {
			map.put("msg", "会员名称不为空!");
			return this.toAddMember(map, request, response);
		}
		map.put("name", request.getParameter("name"));
		map.put("password", request.getParameter("password"));
		map.put("sex", request.getParameter("sex"));
		if (StringUtils.isNotBlank(request.getParameter("birthday"))) {
			map.put("birthday", request.getParameter("birthday"));
		} else {
			if (StringUtils.isNotBlank(request.getParameter("sfzh"))) {
				String sfzh = request.getParameter("sfzh");
				String year = sfzh.substring(6, 10);
				String month = sfzh.substring(10, 12);
				String day = sfzh.substring(12, 14);
				String birth = year + "-" + month + "-" + day;
				map.put("birthday", birth);
			} else {
				map.put("birthday", null);
			}
		}

		map.put("levelId", request.getParameter("level"));
		map.put("tel", request.getParameter("tel"));
		map.put("phone", request.getParameter("phone"));
		map.put("privatePhone", request.getParameter("privatePhone"));
		map.put("officePhone", request.getParameter("officePhone"));
		map.put("homeNumber", request.getParameter("homeNumber"));
		map.put("email", request.getParameter("email"));
		map.put("qq", request.getParameter("QQ"));
		map.put("company", request.getParameter("company"));
		map.put("identity", request.getParameter("sfzh"));
		map.put("identityType", request.getParameter("identityType"));
		map.put("identity", request.getParameter("sfzh"));
		map.put("introduceId", request.getParameter("introduceId"));
		map.put("userId", user.getId());

		String cityId = request.getParameter("inputCity");
		String provId = request.getParameter("inputProvince");
		String areaId = request.getParameter("inputArea");
		String domainId = request.getParameter("domainId");
		// --级联省市区保存
		if (StringUtils.isNotBlank(domainId)) {
			map.put("domainId", Integer.parseInt(domainId));
		}
		if (StringUtils.isNotBlank(areaId)) {
			map.put("areaId", Integer.parseInt(areaId));
		}
		if (StringUtils.isNotBlank(cityId)) {
			map.put("cityId", Integer.parseInt(cityId));
		}
		if (StringUtils.isNotBlank(provId)) {
			map.put("provinceId", Integer.parseInt(provId));
		}

		map.put("address", request.getParameter("address"));
		map.put("remarks", request.getParameter("remarks"));
		java.util.Date time = new java.util.Date();
		map.put("inputTime", time);
		map.put("validityBeginTime", time);
		map.put("validityEndTime", time);

		map.put("wechat", request.getParameter("wechat"));
		map.put("nameEn", request.getParameter("nameEn"));
		map.put("companyAddress", request.getParameter("companyAddress"));
		map.put("duty", request.getParameter("duty"));
		map.put("position", request.getParameter("position"));
		map.put("subStatus", request.getParameter("memberSubStatus"));
		
		//会员卡号
		String cardNo = request.getParameter("memberCardNo");
		if(StringUtils.isNotBlank(cardNo)){
			map.put("cardNumber", cardNo);
		}

		String subMarketingChannel = request
				.getParameter("subMarketingChannel");
		if (StringUtils.isNotBlank(subMarketingChannel)) {
			map.put("subMarketingChannel", subMarketingChannel);
		}

		String marketingSource = request.getParameter("marketingSource");
		if (StringUtils.isNotBlank(marketingSource)) {
			map.put("marketingSource", marketingSource);
		}
		map.put("keeperId", request.getParameter("keeperId"));
		map.put("organizationId", user.getOrganizationId());
		map.put("enable", false);
		map.put("headImgPath", "/app/admin/resources/images/touXiang.jpg");

		try {
			memberService.saveMember(map);
			Long memberId = (Long) map.get("memberId");
			String buy = request.getParameter("buyProductAtSameTime");
			map.clear();
			if ("true".equals(buy)) {// 表示同时购买产品
				return "redirect:toMemberProduct.jhtml?buy=true&memberId=" + memberId.longValue();
			} else {
				return "redirect:toMemberDetail.jhtml?id="+ memberId.longValue();
			}
		} catch (Exception e) {
			map.put("msg", "添加会员失败，请稍候重试或联系管理员!");
			return this.toAddMember(map, request, response);
		}
	}

	// 删除会员
	@RequestMapping(value = "/deleteMember.jhtml")
	public void deletemember(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		String ids = request.getParameter("ids");
		if (StringUtils.isBlank(ids)) {
			msg = "{'success':false,'msg':'未提交待删除会员的编号'}";
		} else {
			String[] arrids = ids.split(",");
			Integer[] deids = new Integer[20];
			for (int i = 0; i < arrids.length; i++) {
				if (arrids[i] != null && !arrids[i].equals("")) {
					deids[i] = Integer.parseInt(arrids[i]);
				}
			}
			try {
				memberService.deleteMemberByIds(deids);
				remainingService.deleteRemainingByIds(deids);
				productRemainingService
						.deleteProductRemainingByMemberIds(deids);
				earlyExperienceService.deleteExperienceByMemberIds(deids);
				msg = "true";
			} catch (RuntimeException re) {
				msg = "false";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 订单中查询会员 */
	@RequestMapping(value = "/ajaxfindmemberinbuyorder.do")
	public void findMemberById(HttpServletRequest request,
			HttpServletResponse response) {
	}

	/** 订单搜索会员时，按Id查找会员 */
	@RequestMapping(value = "/ajaxfindmemberbyid.do")
	public void findByCardNumber(HttpServletRequest request,
			HttpServletResponse response) {
	}

	/** 进入添加会员页 */
	@RequestMapping(value = "/toAddMember.jhtml")
	public String toAddMember(ModelMap context, HttpServletRequest request,
			HttpServletResponse response) {
		super.initFrontHeader(request, context);
		List<Status> status = statusService.findByType(1);// 根据类型查询父类状态
		context.put("memberStatus", status);
		status = statusService.findByType(5);// 根据类型查询父类状态
		context.put("marketingChannels", status);

		List<MemberLevel> memberLevel = memberLevelService.findMemberLevel();// 查询可用会员等级
		context.put("memberLevels", memberLevel);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("level", 1);
		List<Area> areas = areaService.getAreaInPage(map);
		context.put("areas", areas);
		List<Hall> halls = hallService.findHalls();
		context.put("halls", halls);
		context.put("assetsPath", GlobalConstants.ASSETS_PATH);
		// 会籍顾问
		context.put("keepers", userService.findUsersByGroupId("3", this
				.getUser(request).getOrganizationId()));
		return "member_add";
	}

	/** 班级中会员信息 **/
	@RequestMapping(value = "/searchMember_Class.jhtml")
	public String SerchMemberClass(ModelMap model, Map<String, Object> context,
			HttpServletRequest request, HttpServletResponse response) {
		super.initFrontHeader(request, model);

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		String strId = request.getParameter("classId");
		int Id = 0;
		if (!StringUtils.isBlank(strId)) {
			Id = Integer.parseInt(strId);
		}
		/** 查询班级信息,显示在共有的header里 **/
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map1.put("id", Id);
		map1.put("groups", groupIds);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Clazz clazz = clazzService.findById(map1);// 根据ID查询班级
		/** 查询班级会员不安分页查询,用来显示头像 **/
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		List<Member> memberAll = memberService.getMemberAll(map);
		model.put("memberAll", memberAll);
		model.put("name", clazz.getName());
		model.put("state", clazz.getState());
		model.put("assignedTo", clazz.getAssignedTo().getUserDetail().getName());
		model.put("startDate", clazz.getStartDate());
		model.put("endDate", clazz.getEndDate());
		model.put("startWeek", clazz.getStartWeek());
		model.put("endWeek", clazz.getEndWeek());
		model.put("remarks", clazz.getReamarks());
		model.put("productId", clazz.getProduct().getProductId());
		model.put("cheduleList", clazz.getChedules());
		model.put("classId", strId);
		int pageNo = 1;
		int pageSize = 10;
		if (!StringUtils.isBlank(strId)) {
			Id = Integer.parseInt(strId);
		}
		context.put("classId", strId);
		String strStart = request.getParameter("pageNo");// 获得页码数
		if (strStart != null) {
			pageNo = Integer.parseInt(strStart);
		}
		String strLimit = request.getParameter("limit");
		if (strLimit != null) {
			pageSize = Integer.parseInt(strLimit);
		}

		PaginatedList<Member> p = memberService.getMemberInPage(
				(pageNo - 1) * 10, pageSize, map);
		context.put("members", p);
		return "member_class";
	}

	// 导出会员
	@RequestMapping(value = "/exportMember.jhtml")
	public void exportMember(String cardnumber, String name, String company,
			String keeper, String minAge, String maxAge, String memberLevel,
			String nameEn, String phone, String domainId, String provinceId,
			String cityId, String areaId, String email, String substatus,
			String memberStatuCode, String subMarketingChannel,
			String startdate1, String startdate2, String marketingChannel,
			ModelMap context, HttpServletRequest request,
			HttpServletResponse response) {

		super.initFrontHeader(request, context);
		int pageNo = 1;
		String strStart = request.getParameter("pageNo");// 获得页码数
		if (StringUtils.isNotBlank(strStart)) {
			pageNo = Integer.parseInt(strStart);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(cardnumber)) {
			map.put("cardnumber", "%" + cardnumber + "%");
		}
		if (StringUtils.isNotBlank(name)) {
			map.put("name", "%" + name + "%");
		}
		if (StringUtils.isNotBlank(nameEn)) {
			map.put("nameEn", "%" + nameEn + "%");
		}
		if (StringUtils.isNotBlank(phone)) {
			map.put("phone", "%" + phone + "%");
		}
		if (StringUtils.isNotBlank(startdate1)) {// 查询创建时间
			map.put("startdate1", startdate1);
		}
		if (StringUtils.isNotBlank(startdate2)) {
			map.put("startdate2", startdate2);
		}
		if (StringUtils.isNotBlank(company)) {
			map.put("company", "%" + company + "%");
		}
		if (StringUtils.isNotBlank(memberLevel)) {
			map.put("memberLev", memberLevel);
		}
		if (StringUtils.isNotBlank(keeper)) {
			map.put("keeperId", keeper);
		}
		if (StringUtils.isNotBlank(email)) {
			map.put("email", email);
		}
		if (StringUtils.isNotBlank(domainId)) {
			map.put("domainId", domainId);
		}
		if (StringUtils.isNotBlank(provinceId)) {
			map.put("provinceId", provinceId);
		}
		if (StringUtils.isNotBlank(cityId)) {
			map.put("cityId", cityId);
		}
		if (StringUtils.isNotBlank(areaId)) {
			map.put("areaId", areaId);
		}
		if (StringUtils.isNotBlank(subMarketingChannel)) {
			map.put("subMarketingChannel", subMarketingChannel);
		}
		if (StringUtils.isNotBlank(marketingChannel)) {
			map.put("marketingChannelCode", marketingChannel);
		}
		if (StringUtils.isNotBlank(memberStatuCode)) {
			map.put("statusCode", memberStatuCode);
		}
		if (StringUtils.isNotBlank(substatus)) {
			map.put("substatus", substatus);
		}

		// 卡外码
		String outsideCardNo = request.getParameter("outsideCardNo");
		if (StringUtils.isNotBlank(outsideCardNo)) {
			map.put("outsideCardNo", "%" + outsideCardNo + "%");
		}
		// 唯一性产品
		String memberProductId = request.getParameter("memberProductId");
		if (StringUtils.isNotBlank(memberProductId)) {
			map.put("memberProductId", memberProductId);
		}

		// 会员到期时间
		context.put("memberExpireDate", new Date());
		map.put("memberExpireDate", new Date());

		if (StringUtils.isNotBlank(minAge)) {
			Calendar cal = Calendar.getInstance();
			int y = cal.get(Calendar.YEAR) - Integer.parseInt(minAge);
			cal.set(y, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			map.put("maxTime", cal.getTime());
		}
		if (StringUtils.isNotBlank(maxAge)) {
			Calendar cal = Calendar.getInstance();
			int y = cal.get(Calendar.YEAR) - Integer.parseInt(maxAge);
			cal.set(y, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			map.put("minTime", cal.getTime());
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Member> p = memberService.getMemberInPage(
				(pageNo - 1) * 10, Integer.MAX_VALUE, map);
		MemberExportTemplate template = new MemberExportTemplate(p);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response,
				"会员信息表.xlsx");

		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 会员搜索
	@RequestMapping(value = "/searchMember.jhtml")
	public String SearchMember(String cardnumber, String name, String company,
			String keeper, String minAge, String maxAge, String memberLevel,
			String nameEn, String phone, String domainId, String provinceId,
			String cityId, String areaId, String email, String substatus,
			String memberStatuCode, String infoSource, String startdate1,
			String subMarketingChannel, String startdate2, String shou,
			String marketingChannel, String display, Integer syjq,
			Integer syts, Integer sycs, Integer mglts, Integer mgzts,
			ModelMap context, HttpServletRequest request,
			HttpServletResponse response) {

		super.initFrontHeader(request, context);
		if ("block".equals(display)) {
			context.put("display", "block");
		}
		int pageNo = 1;
		int pageSize = 10;

		String strStart = request.getParameter("pageNo");// 获得页码数
		if (StringUtils.isNotBlank(strStart)) {
			pageNo = Integer.parseInt(strStart);
		}
		String strLimit = request.getParameter("limit");
		if (strLimit != null) {
			pageSize = Integer.parseInt(strLimit);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(cardnumber)) {
			map.put("cardnumber", "%" + cardnumber + "%");
			context.put("cardnumber", cardnumber);
		}

		// 卡外码
		String outsideCardNo = request.getParameter("outsideCardNo");
		if (StringUtils.isNotBlank(outsideCardNo)) {
			map.put("outsideCardNo", "%" + outsideCardNo + "%");
			context.put("outsideCardNo", outsideCardNo);
		}
		// 唯一性产品
		String memberProductId = request.getParameter("memberProductId");
		if (StringUtils.isNotBlank(memberProductId)) {
			map.put("memberProductId", memberProductId);
			context.put("memberProductId", memberProductId);
		}
		
		//累计多长时间未出席
		String totalAbsent = request.getParameter("total_absent");
		if(StringUtils.isNotBlank(totalAbsent)){
			map.put("totalAbsent", Integer.valueOf(totalAbsent));
			context.put("totalAbsent", Integer.valueOf(totalAbsent));
		}

		if (StringUtils.isNotBlank(name)) {
			map.put("name", "%" + name + "%");
			context.put("name", name);
		}
		if (StringUtils.isNotBlank(nameEn)) {
			map.put("nameEn", "%" + nameEn + "%");
			context.put("nameEn", nameEn);
		}
		if (StringUtils.isNotBlank(startdate1)) {// 查询创建时间
			map.put("startdate1", startdate1);
			context.put("startdate1", startdate1);
		}
		if (StringUtils.isNotBlank(startdate2)) {
			map.put("startdate2", startdate2);
			context.put("startdate2", startdate2);
		}
		if (StringUtils.isNotBlank(startdate1)
				&& StringUtils.isNotBlank(startdate2)
				&& startdate1.equals(startdate2)) {
			String time1 = startdate1.trim() + " 00:00:00";
			String time2 = startdate2.trim() + " 23:59:59";
			map.put("startdate1", time1);
			map.put("startdate2", time2);
		}
		if (StringUtils.isNotBlank(phone)) {
			map.put("phone", "%" + phone + "%");
			context.put("phone", phone);
		}
		if (StringUtils.isNotBlank(shou)) {
			map.put("shou", shou.trim());
			context.put("shou", shou.trim());
		}
		if (StringUtils.isNotBlank(company)) {
			map.put("company", "%" + company + "%");
			context.put("company", company);
		}
		if (StringUtils.isNotBlank(memberLevel)) {
			map.put("memberLev", memberLevel);
			context.put("memberLev", Integer.parseInt(memberLevel));
		}
		if (StringUtils.isNotBlank(keeper)) {
			map.put("keeperId", keeper);
			context.put("keeperId", keeper);
		}
		if (StringUtils.isNotBlank(email)) {
			map.put("email", email);
			context.put("email", email);
		}
		if (StringUtils.isNotBlank(domainId)) {
			map.put("domainId", domainId);
			context.put("domainId", domainId);
		}
		if (StringUtils.isNotBlank(provinceId)) {
			map.put("provinceId", provinceId);
			context.put("provinceId", provinceId);
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("level", 2);
			map1.put("parentId", provinceId);
			List<Area> areas = areaService.getAreaInPage(map1);
			context.put("citys", areas);
		}
		if (StringUtils.isNotBlank(cityId)) {
			map.put("cityId", cityId);
			context.put("cityId", cityId);
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("level", 3);
			map1.put("parentId", cityId);
			List<Area> areas = areaService.getAreaInPage(map1);
			context.put("areas", areas);
		}
		if (StringUtils.isNotBlank(areaId)) {
			map.put("areaId", areaId);
			context.put("areaId", areaId);
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("level", 4);
			map1.put("parentId", areaId);
			List<Area> areas = areaService.getAreaInPage(map1);
			context.put("domains", areas);
		}
		if (StringUtils.isNotBlank(subMarketingChannel)) {
			map.put("subMarketingChannel", subMarketingChannel);
			context.put("subMarketingChannel", subMarketingChannel);
		}
		if (StringUtils.isNotBlank(marketingChannel)) {
			map.put("marketingChannelCode", marketingChannel);
			context.put("marketingChannelCode", marketingChannel);
		}

		// 会员状态
		if (StringUtils.isNotBlank(memberStatuCode)) {
			map.put("statusCode", memberStatuCode);
			context.put("statusCode", memberStatuCode);
		}

		if (StringUtils.isNotBlank(substatus)) {
			map.put("substatus", substatus);
			context.put("substatus", substatus);
		}
		// 会员到期时间
		context.put("memberExpireDate", new Date());
		map.put("memberExpireDate", new Date());

		if (StringUtils.isNotBlank(infoSource)) {
			map.put("infoSource", infoSource);
			context.put("infoSource", infoSource);
		}

		if (StringUtils.isNotBlank(minAge)) {
			Calendar cal = Calendar.getInstance();
			int y = cal.get(Calendar.YEAR) - Integer.parseInt(minAge);
			cal.set(y, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			map.put("maxTime", cal.getTime());
			context.put("minAge", minAge);
		}
		if (StringUtils.isNotBlank(maxAge)) {
			Calendar cal = Calendar.getInstance();
			int y = cal.get(Calendar.YEAR) - Integer.parseInt(maxAge);
			cal.set(y, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			map.put("minTime", cal.getTime());
			context.put("maxAge", maxAge);
		}

		if (syjq != null || syjq != null || sycs != null || mglts != null
				|| mgzts != null) {
			context.put("zysr", "true");
		}
		/*** 主页搜索条件 ****/
		Calendar c = null;
		// --少于多少钱的会员
		if (syjq != null) {
			map.put("syje", syjq);
			context.put("syje", syjq);
		}
		// --少于多少天的会员
		if (syts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, syts);
			map.put("syts", c.getTime());
			context.put("syts", syts);
		}
		// --少于多少次的会员
		if (sycs != null) {
			map.put("sycs", sycs);
			context.put("sycs", sycs);
		}
		// --多少天没有过来的会员
		if (mglts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, -mglts);
			String sj = DateTimeUtils.getInstance().format(c.getTime(),
					"yyyy-MM-dd");
			System.out.print(sj);
			map.put("mglts", c.getTime());
			context.put("mglts", mglts);
			// --查询所有正式会员member
			List<String> zshyjh = new ArrayList<String>();
			List<Status> statuses = statusService.findByParentCode("0003");
			for (Status s : statuses) {
				zshyjh.add(s.getCode());
			}
			map.put("zshyjh", zshyjh);
		}
		// --多少天没有跟踪的会员
		if (mgzts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, -mgzts);
			map.put("mgzts", c.getTime());
			String sj = DateTimeUtils.getInstance().format(c.getTime(),
					"yyyy-MM-dd");
			System.out.print(sj);
			context.put("mgzts", mgzts);
			List<String> zghyjh = new ArrayList<String>();
			// --未到访客
			zghyjh.add("0005");
			zghyjh.add("0006");
			zghyjh.add("0009");
			// --访客
			zghyjh.add("0013");
			zghyjh.add("0014");
			zghyjh.add("0015");
			zghyjh.add("0016");
			// --正式会员
			zghyjh.add("0020");
			zghyjh.add("0021");
			zghyjh.add("0022");
			map.put("zghyjh", zghyjh);
		}
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Member> p = null;
		int totalspeakers = 0;
		if ("block".equals(display)) {
			p = memberService.getMemberInPage((pageNo - 1) * 10, pageSize, map);
			totalspeakers = p.getPager().getCountOfTotalResults().intValue();
		}
		context.put("members", p);
		context.put("totalspeakers", totalspeakers);
		List<Status> status = statusService.findByType(1);// 根据类型查询父类状态
		context.put("memberStatus", status);
		if (subMarketingChannel != null && !subMarketingChannel.equals("")) {
			Status stat = statusService.findByCode(subMarketingChannel);

			context.put("marketingChannelCode", stat.getParentcode());
			status = statusService.findByParentCode(stat.getParentcode());
			context.put("subMarketingChannels", status);
		}
		status = statusService.findByType(5);// 根据类型查询父类状态
		context.put("marketingChannels", status);
		if (substatus != null && !substatus.equals("")) {
			Status stat = statusService.findByCode(substatus);
			context.put("statusCode", stat.getParentcode());
			status = statusService.findByParentCode(stat.getParentcode());
			context.put("subStatuses", status);
		}
		map.put("level", 1);
		List<Area> areas = areaService.getAreaInPage(map);
		context.put("provinces", areas);

		// 产品名称
		Map<String, Object> mapProducts = new HashMap<String, Object>();
		mapProducts.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> memberProducts = productService.findProductAvailable(1,
				Integer.MAX_VALUE, mapProducts);
		context.put("memberProducts", memberProducts);

		List<MemberLevel> memberLevels = memberLevelService.findMemberLevel();// 查询可用会员等级
		context.put("memberLevels", memberLevels);
		// 查询会籍顾问
		List<GroupUserModel> keepers = userService.findUsersByGroupId("3", this
				.getUser(request).getOrganizationId());
		context.put("keeper", keepers);

		// --会员导入模板文件
		context.put("mbName", "会员导入模板.xlsx");
		return "member_search";
	}

	// 进入会员信息详情页
	@RequestMapping(value = "/toMemberDetail.jhtml")
	public String toMemberDetail(ModelMap context, Integer id,
			HttpServletRequest request, HttpServletResponse response) {

		super.initFrontHeader(request, context);

		context.put("assetsPath", GlobalConstants.ASSETS_PATH);
		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map1.put("groups", groupIds);
		map1.put("id", id);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map1);
		context.put("member", member);
		if (member.getBirthday() != null) {
			Date date = new Date();
			long day = (date.getTime() - member.getBirthday().getTime())
					/ (24 * 60 * 60 * 1000) + 1;
			String year = new DecimalFormat("#").format(day / 365f);
			context.put("nianling", year);
		}

		List<Status> status = statusService.findByType(1);// 根据类型查询父类状态
		context.put("memberStatus", status);
		if (member.getSubstatus() != null && !member.getSubstatus().equals("")) {
			Status stat = statusService.findByCode(member.getSubstatus());
			context.put("statu", stat);
			status = statusService.findByParentCode(stat.getParentcode());
			context.put("subStatuses", status);
			stat = statusService.findByCode(stat.getParentcode());
			context.put("parentStatu", stat);
		}
		List<MemberLevel> memberLevel = memberLevelService.findMemberLevel();// 查询可用会员等级
		context.put("memberLevels", memberLevel);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("level", 1);
		List<Area> areas = areaService.getAreaInPage(map);
		context.put("provinces", areas);
		if (member.getProvinceId() != null) {
			context.put("provinceId", member.getProvinceId());
			map.put("level", 2);
			map.put("parentId", member.getProvinceId());
			areas = areaService.getAreaInPage(map);
			context.put("citys", areas);
		}
		if (member.getCityId() != null) {
			context.put("cityId", member.getCityId());
			map.put("level", 3);
			map.put("parentId", member.getCityId());
			areas = areaService.getAreaInPage(map);
			context.put("areas", areas);
		}
		if (member.getAreaId() != null) {
			context.put("areaId", member.getAreaId());
			map.put("level", 4);
			map.put("parentId", member.getAreaId());
			areas = areaService.getAreaInPage(map);
			context.put("domains", areas);
		}
		if (member.getDomainId() != null) {
			context.put("domainId", member.getDomainId());
		}
		List<Hall> halls = hallService.findHalls();
		context.put("halls", halls);
		if (StringUtils.isNotBlank(member.getOrganizationId())) {
			Hall memberHall = hallService
					.findByCode(member.getOrganizationId());
			context.put("memberHall", memberHall);
		}
		return "member_detail";
	}

	// 会员信息修改
	@RequestMapping(value = "/toEditMemberDetail.jhtml")
	public String toEditMemberDetail(ModelMap map, Integer id,
			HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> map1 = new HashMap<String, Object>();
		List<Integer> groupIds1 = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds1.add(group.getId());
		}
		map1.put("groups", groupIds1);
		map1.put("id", id);
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map1);
		String name = request.getParameter("name");
		if (StringUtils.isNotBlank(name)) {
			member.setName(name);
		}
		String sex = request.getParameter("sex");
		if (StringUtils.isNotBlank(sex)) {
			member.setSex(sex);
		}
		MemberLevel level = new MemberLevel();
		String levelId = request.getParameter("inputMemberLevel");
		if (StringUtils.isNotBlank(levelId)) {
			level.setMemberLevelId(Integer.parseInt(levelId));
			member.setLevel(level);
		}
		String birthday = request.getParameter("birthday");
		if (StringUtils.isNotBlank(birthday)) {
			member.setBirthday(DateTimeUtils.getInstance().parse(birthday,
					"yyyy-MM-dd"));
		}
		member.setTel(request.getParameter("tel"));
		member.setPhone(request.getParameter("phone"));
		member.setPrivatePhone(request.getParameter("privatePhone"));
		member.setOfficePhone(request.getParameter("officePhone"));
		member.setHomeNumber(request.getParameter("homeNumber"));
		member.setEmail(request.getParameter("email"));
		member.setQq(request.getParameter("QQ"));
		member.setAddress(request.getParameter("address"));
		member.setCompany(request.getParameter("company"));
		String identityType = request.getParameter("identityType");
		if (StringUtils.isNotBlank(identityType)) {
			member.setIdentitytype(Integer.parseInt(identityType));
		}
		member.setIdentity(request.getParameter("identity"));
		member.setCompanyaddress(request.getParameter("companyAddress"));
		member.setDuty(request.getParameter("duty"));
		member.setNameEn(request.getParameter("nameEn"));
		member.setWechat(request.getParameter("wechat"));
		String keeperId = request.getParameter("keeperId");
		// 会籍顾问
		if (StringUtils.isNotBlank(keeperId)) {
			member.setKeeperId(keeperId);
		}
		// 市场推广人
		// if (StringUtils.isNotBlank(promoterId)) {
		// member.setPromoterId(promoterId);
		// }
		member.setPosition(request.getParameter("position"));
		member.setRemarks(request.getParameter("remarks"));
		member.setSubstatus(request.getParameter("memberSubStatus"));

		String cityId = request.getParameter("inputCity");
		String provId = request.getParameter("inputProvince");
		String areaId = request.getParameter("inputArea");
		String domainId = request.getParameter("domainId");
		// --级联省市区保存
		// --首先判断是否选中区域
		if (StringUtils.isNotBlank(domainId)) {
			member.setDomainId(Integer.parseInt(domainId));
		} else {
			member.setDomainId(null);
		}
		if (StringUtils.isNotBlank(areaId)) {
			member.setAreaId(Integer.parseInt(areaId));
		} else {
			member.setAreaId(null);
		}
		if (StringUtils.isNotBlank(cityId)) {
			member.setCityId(Integer.parseInt(cityId));
		} else {
			member.setCityId(null);
		}
		if (StringUtils.isNotBlank(provId)) {
			member.setProvinceId(Integer.parseInt(provId));
		} else {
			member.setProvinceId(null);
		}

		// 卡外码
		String outsideCardNo = request.getParameter("outsideCardNo");
		if (StringUtils.isNotBlank(outsideCardNo)) {
			member.setOutsideCardNo(outsideCardNo);
		} else {
			member.setOutsideCardNo(null);
		}

		String imgpath = request.getParameter("headimgpath");
		if (StringUtils.isNotBlank(imgpath)) {
			member.setHeadimgpath(imgpath);
		}
		if (StringUtils.isBlank(request.getParameter("cardNumber"))
				|| request.getParameter("cardNumber").equals(
						member.getCardnumber())) {
			if (memberService.updateMember(member)) {
				map.clear();
				return "redirect:toMemberDetail.jhtml?id=" + id;
			} else {
				map.put("msg", "修改会员失败，请稍候重试或联系管理员!");
			}
		} else {
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("columnName", "cardNumber");
			map2.put("value", request.getParameter("cardNumber"));
			List<Integer> groupIds = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds.add(group.getId());
			}
			map2.put("groups", groupIds);
			map2.put("hallcode", this.getUser(request).getOrganizationId());
			if (memberService.findByCardNumber(map2) == null) {
				member.setCardnumber(request.getParameter("cardNumber"));
				if (memberService.updateMember(member)) {
					map.clear();
					return "redirect:toMemberDetail.jhtml?id=" + id;
				} else {
					map.put("msg", "修改会员失败，请稍候重试或联系管理员!");
				}
			} else {
				map.put("msg", "会员卡号已存在!");
			}
		}
		return this.toMemberDetail(map, id, request, response);
	}

	// 进入会员市场来源页，查询会员信息
	@RequestMapping(value = "/toMemberMarketingSource.jhtml")
	public String toMemberMarketingSource(ModelMap context, Integer id,
			HttpServletRequest request, HttpServletResponse response) {

		super.initFrontHeader(request, context);

		context.put("assetsPath", GlobalConstants.ASSETS_PATH);

		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("id", id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map);
		context.put("member", member);
		// 会员类型
		List<Status> memberStatus = statusService.findByType(1);// 根据类型查询父类状态
		context.put("memberStatus", memberStatus);
		if (StringUtils.isNotBlank(member.getSubstatus())) {
			Status stat = statusService.findByCode(member.getSubstatus());
			context.put("statu", stat);
			memberStatus = statusService.findByParentCode(stat.getParentcode());
			context.put("subStatuses", memberStatus);
			stat = statusService.findByCode(stat.getParentcode());
			context.put("parentStatu", stat);
		}

		List<Status> status = statusService.findByType(5);// 查询市场渠道
		context.put("marketingChannels", status);
		// 会籍顾问
		context.put("keepers", userService.findUsersByGroupId("3", this
				.getUser(request).getOrganizationId()));
		if (StringUtils.isNotBlank(member.getSubmarketingchannel())) {
			Status statu = statusService.findById(Integer.parseInt(member
					.getSubmarketingchannel()));
			context.put("code", statu.getCode());
			context.put("parentCode", statu.getParentcode());
			List<Status> status2 = statusService.findByParentCode(statu
					.getParentcode());// 查询通类子渠道
			context.put("submarketingchannels", status2);
		}
		return "member_marketingSource";
	}

	// 进入会员商品列表，查询会员购买商品记录
	@RequestMapping(value = "/toMemberGoods.jhtml")
	public String toMemberGoods(ModelMap context, Integer id,
			HttpServletRequest request, HttpServletResponse response) {

		super.initFrontHeader(request, context);

		context.put("assetsPath", GlobalConstants.ASSETS_PATH);
		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("id", id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map);
		context.put("member", member);
		// 会员类型
		List<Status> memberStatus = statusService.findByType(1);// 根据类型查询父类状态
		context.put("memberStatus", memberStatus);
		if (member.getSubstatus() != null && !member.getSubstatus().equals("")) {
			Status stat = statusService.findByCode(member.getSubstatus());
			context.put("statu", stat);
			memberStatus = statusService.findByParentCode(stat.getParentcode());
			context.put("subStatuses", memberStatus);
			stat = statusService.findByCode(stat.getParentcode());
			context.put("parentStatu", stat);
		}
		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}
		if (pageNo != null) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		PaginatedList<GoodsOrderDetail> goodsOrderDetails = goodsOrderDetailService
				.getGoodsOrderDetailInPage(id, start, limit);
		context.put("goodsOrderDetails", goodsOrderDetails);
		return "member_goods";
	}

	// 修改会员市场信息来源
	@RequestMapping(value = "/editMarketingSource.jhtml")
	public String editMarketingSource(ModelMap context, Integer id,
			String marketingSource, String subMarketingChannel,
			String keeperId, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("id", id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map);
		member.setMarketingsource(marketingSource);
		member.setSubmarketingchannel(subMarketingChannel);
		// 会籍顾问
		if (StringUtils.isNotBlank(keeperId)) {
			member.setKeeperId(keeperId);
		}
		if (memberService.updateMember(member)) {// 修改会员信息
			return "redirect:toMemberMarketingSource.jhtml?id=" + id;
		} else {
			context.put("msg", "修改失败，请联系管理员!");
			return this.toMemberMarketingSource(context, id, request, response);
		}

	}

	// 去往商品购买页
	@RequestMapping(value = "/toBuyGoods.jhtml")
	public String toBuyGoods(ModelMap context, Integer id,
			HttpServletRequest request, HttpServletResponse response) {
		super.initFrontHeader(request, context);

		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("id", id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		Member member = memberService.findById(map);
		context.put("member", member);
		context.put("memberRemaining", member.getRemaining().getRemaining());
		// 查询全部商品
		List<Goods> goodsList = goodservive.findAllByOrganizationId(member
				.getOrganizationId());
		context.put("goodsList", goodsList);
		// 查找购买产品的负责人,供购买时选择...
		List<GroupUserModel> respors = userService.findUsersByGroupId("4", this
				.getUser(request).getOrganizationId());
		context.put("responsibleList", respors);

		return "member_goodsBuy";
	}

	@RequestMapping(value = "/ajaxUpdateHeadImgByMemberId.jhtml")
	public void ajaxUpdateHeadImgByMemberId(HttpServletRequest request,
			HttpServletResponse response) {
		String memberId = request.getParameter("memberId");
		String headImgPath = request.getParameter("headImgPath");

		Map<String, String> params = new HashMap<String, String>();
		params.put("memberId", memberId);
		params.put("memberHeadImg", headImgPath);

		boolean b = this.memberService.updateMemberHeadImg(params);
		if (b) {
			WebAppUtils.ajaxResponse(response, "{\"success\":true}");
		} else {
			WebAppUtils.ajaxResponse(response, "{\"success\":false}");
		}
	}

	// 前台操作页面更新会员头像
	@RequestMapping(value = "/seatUpdateMemberHeadImg.jhtml")
	public String seatUploadMemberHeadImg(
			ModelMap context,
			@RequestParam(value = "headImgPath", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		String src = "";
		if (file != null) {
			src = this.uploadImg(file, request, response);

		}
		String memberId = request.getParameter("memberId");
		if (!StringUtils.isBlank(memberId)) {
			Map<String, String> params = new HashMap<String, String>();
			String path = request.getServletContext().getRealPath("/");
			params.put("memberId", memberId);
			params.put("memberHeadImg", src);
			params.put("path", path);
			this.memberService.updateMemberHeadImg(params);
			context.put("src", src);
		}
		return "uploadImg";
	}

	// 删除会员
	@RequestMapping(value = "/toUpdateMemberHeadImg.jhtml")
	public String toUploadMemberHeadImg(
			ModelMap context,
			@RequestParam(value = "headImgPath", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		String src = "";
		if (file != null) {
			src = this.uploadImg(file, request, response);
		}
		context.put("src", src);
		return "uploadImg";
	}

	@RequestMapping(value = "/toUploadFile.jhtml")
	public String toUploadFile(
			@RequestParam(value = "xlsfile", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		super.initFrontHeader(request, model);
		User user = this.getUser(request);
		String msg = "";
		String key = "";
		String origName = file.getOriginalFilename();// 原始文件名，即上传的文件名
		String ext = FilenameUtils.getExtension(origName).toLowerCase();// 文件扩展名
		String uploaddir = "/upload/";
		String realpath = request.getServletContext().getRealPath(uploaddir);
		File filedir = new File(realpath);
		if (!filedir.exists()) {
			filedir.mkdirs();
		}
		try {
			if (!realpath.endsWith(File.separator)) {
				realpath += File.separator;
			}
			File file1 = new File(realpath);
			if (!file1.exists()) {
				file1.mkdirs();
			}

			String uuid = FILE_DATEFORMAT.format(new Date())
					+ RandomStringUtils.random(10, ZhuwNum62.N36_CHARS);
			String filename = uuid + "." + ext;

			File tempFile = new File(realpath + filename);
			file.transferTo(tempFile);
			String fileUrl = tempFile.getName();
			fileUrl = uploaddir + fileUrl;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("organizationId", user.getOrganizationId());
			map.put("userId", user.getId());
			map.put("enable", false);
			map.put("headImgPath", "/app/admin/resources/images/touXiang.jpg");
			List<Integer> groupIds = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds.add(group.getId());
			}
			map.put("groups", groupIds);
			map.put("hallcode", this.getUser(request).getOrganizationId());
			String info = this.memberService.importMemberFromExcel(tempFile,
					map);
			String[] infos = info.split("#");
			if (infos != null && infos.length > 0) {
				key = infos[0];
				String count = infos[1];
				model.put("total", count);
				if (StringUtils.isNotBlank(key) && "5".equals(key)) {
					String efInfo = infos[2];
					msg = efInfo;
					if (StringUtils.isNotBlank(efInfo) && efInfo.length() > 2) {
						efInfo = efInfo.substring(1, efInfo.length() - 1);
						String[] efInfos = efInfo.split("~");
						// --"11:[111：2223：33!+]"
						String eInfo = efInfos[0];
						String fInfo = efInfos[1];
						if (StringUtils.isNotBlank(eInfo) && eInfo.length() > 2) {
							String[] eInfos = eInfo.split(":");
							String[] fInfos = fInfo.split(":");
							String ecount = "";
							String fcount = "";
							String cfInfo = "";
							String ffInfo = "";
							if (eInfos != null && eInfos.length > 0) {
								// --重复的数据
								ecount = eInfos[0];
								if (StringUtils.isNotBlank(ecount)
										&& !"0".equals(ecount)) {
									cfInfo = eInfos[1];
									cfInfo = cfInfo.substring(1,
											cfInfo.length() - 1);
								} else {
									ecount = "0";
								}
							}

							if (fInfos != null && fInfos.length > 0) {
								// --失败数据
								fcount = fInfos[0];
								if (StringUtils.isNotBlank(fcount)
										&& !"0".equals(fcount)) {
									ffInfo = fInfos[1];
									ffInfo = ffInfo.substring(1,
											ffInfo.length() - 1);
								} else {
									fcount = "0";
								}
							}
							model.put("ecount", ecount);
							model.put("fcount", fcount);
							model.put("cfInfo", cfInfo);
							model.put("ffInfo", ffInfo);
						}
					}
				}
			}
			filedir.delete();
			tempFile.delete();
		} catch (Exception e) {
			logger.error("文件上传异常", e);
		}
		model.put("msg", msg);
		model.put("key", key);
		return "redirect:searchMember.jhtml";
	}

	// 上传图片
	public String uploadImg(MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {

		String origName = file.getOriginalFilename();// 原始文件名，即上传的文件名
		if (origName == null || origName.equals("")) {
			return null;
		}
		String ext = FilenameUtils.getExtension(origName).toLowerCase();// 文件扩展名
		String uploaddir = "/upload/";
		String realpath = request.getServletContext().getRealPath(uploaddir);
		File filedir = new File(realpath);
		if (!filedir.exists()) {
			filedir.mkdirs();
		}
		try {
			if (!realpath.endsWith(File.separator)) {
				realpath += File.separator;
			}
			File file1 = new File(realpath);
			if (!file1.exists()) {
				file1.mkdirs();
			}

			String uuid = FILE_DATEFORMAT.format(new Date())
					+ RandomStringUtils.random(10, ZhuwNum62.N36_CHARS);
			String filename = uuid + "." + ext;

			File tempFile = new File(realpath + filename);
			file.transferTo(tempFile);
			String fileUrl = tempFile.getName();
			fileUrl = uploaddir + fileUrl;
			return fileUrl;
		} catch (Exception e) {
			logger.error("图片上传异常", e);
			return null;
		}
	}

	//
	@RequestMapping(value = "/updateEarlyExperience.jhtml")
	public void updateEarlyExperience(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", request.getParameter("id"));
		map.put("column1", request.getParameter("column1"));
		map.put("value1", request.getParameter("value"));
		map.put("column2", request.getParameter("column2"));
		String time = DateTimeUtils.getInstance().format(new Date(),
				"yyyy-MM-dd HH:mm:ss");
		map.put("value2", time);
		try {
			if (earlyExperienceService.updateEarlyExperience(map)) {
				// Member
				// member=this.memberService.findById(Integer.parseInt(request.getParameter("id")));
				// String str=member.getSubstatus();
				// if(StringUtils.isNotBlank(str)){
				// Status
				// status=this.statusService.findByCode(member.getSubstatus());
				// if(status!=null&&status.getParentcode().equals("0001")){
				// member.setSubstatus("0016");
				// memberService.updateMember(member);
				// }
				// }else{
				// member.setSubstatus("0016");
				// memberService.updateMember(member);
				// }
				msg = "{\"success\":true,\"val\":\"" + time + "\"}";
			} else {
				msg = "{\"success\":false,\"val\":\"修改失败，请联系管理员！\"}";
			}
		} catch (RuntimeException re) {
			re.printStackTrace();
			msg = "{\"success\":false,\"val\":\"修改失败，请联系管理员！\"}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	public ClazzService getClazzService() {
		return clazzService;
	}

	public void setClazzService(ClazzService clazzService) {
		this.clazzService = clazzService;
	}

	public CoachService getCoachService() {
		return coachService;
	}

	public void setCoachService(CoachService coachService) {
		this.coachService = coachService;
	}

	public CheduleService getCheduleService() {
		return cheduleService;
	}

	public void setCheduleService(CheduleService cheduleService) {
		this.cheduleService = cheduleService;
	}

	public PlaceService getPlaceService() {
		return placeService;
	}

	public void setPlaceService(PlaceService placeService) {
		this.placeService = placeService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public RemainingService getRemainingService() {
		return remainingService;
	}

	public void setRemainingService(RemainingService remainingService) {
		this.remainingService = remainingService;
	}

	public ProductRemainingService getProductRemainingService() {
		return productRemainingService;
	}

	public void setProductRemainingService(
			ProductRemainingService productRemainingService) {
		this.productRemainingService = productRemainingService;
	}

	public AreaService getAreaService() {
		return areaService;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public StatusService getStatusService() {
		return statusService;
	}

	public void setStatusService(StatusService statusService) {
		this.statusService = statusService;
	}

	public MemberLevelService getMemberLevelService() {
		return memberLevelService;
	}

	public void setMemberLevelService(MemberLevelService memberLevelService) {
		this.memberLevelService = memberLevelService;
	}

	public HallService getHallService() {
		return hallService;
	}

	public void setHallService(HallService hallService) {
		this.hallService = hallService;
	}

	public GoodsOrderDetailService getGoodsOrderDetailService() {
		return goodsOrderDetailService;
	}

	public void setGoodsOrderDetailService(
			GoodsOrderDetailService goodsOrderDetailService) {
		this.goodsOrderDetailService = goodsOrderDetailService;
	}

	public GoodsService getGoodservive() {
		return goodservive;
	}

	public void setGoodservive(GoodsService goodservive) {
		this.goodservive = goodservive;
	}

	public EarlyExperienceService getEarlyExperienceService() {
		return earlyExperienceService;
	}

	public void setEarlyExperienceService(
			EarlyExperienceService earlyExperienceService) {
		this.earlyExperienceService = earlyExperienceService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(value = "/searchTrackMembers.jhtml")
	public String searchTrackMembers(Integer syjq, Integer syts, Integer sycs,
			Integer mglts, Integer mgzts, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);
		int start = 0;
		int limit = 10;

		Map<String, Object> map = new HashMap<String, Object>();
		Calendar c = null;
		// --少于多少钱的会员
		if (syjq != null) {
			map.put("syjq", syjq);
		}
		// --少于多少天的会员
		if (syts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, syts);
			map.put("syts", c.getTime());
		}
		// --少于多少次的会员
		if (sycs != null) {
			map.put("sycs", sycs);
		}
		// --多少天没有过来的会员
		if (mglts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, mglts);
			map.put("mglts", mglts);
		}
		// --多少天没有跟踪的会员
		if (mgzts != null) {
			c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, mgzts);
			map.put("mgzts", mgzts);
		}
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Member> p = memberService.getMemberInPage(start, limit,
				map);
		// --前台展示
		int totalspeakers = p.getPager().getCountOfTotalResults().intValue();
		model.put("members", p);
		model.put("totalspeakers", totalspeakers);
		List<Status> status = statusService.findByType(1);// 根据类型查询父类状态
		model.put("memberStatus", status);

		status = statusService.findByType(5);// 根据类型查询父类状态
		model.put("marketingChannels", status);

		map.put("level", 1);
		List<Area> areas = areaService.getAreaInPage(map);
		model.put("provinces", areas);

		List<MemberLevel> memberLevels = memberLevelService.findMemberLevel();// 查询可用会员等级
		model.put("memberLevels", memberLevels);
		// 查询会籍顾问
		List<GroupUserModel> keepers = userService.findUsersByGroupId("3", this
				.getUser(request).getOrganizationId());
		model.put("keeper", keepers);

		// --会员导入模板文件
		model.put("mbName", "会员导入模板.xlsx");
		return "member_search";
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
}
